import json
from pathlib import Path

from ctaf_core.ctaf_objects.base_exception import CTAFbaseException
from ctaf_facade.enumerations.error_code_enum import ErrorCodeEnum


def get_file_path(filename: str, abs_file_path: Path = None) -> Path:
    #use current work directory
    if not abs_file_path:
        cwd: Path = Path.cwd()
        file_path: Path = cwd.joinpath(filename)
        #if file_path is directory and not exists, then make it
        check_and_create_dir(file_path)
        return file_path
    else:
        return abs_file_path.joinpath(filename)

def check_and_create_dir(path: Path):
    if not path.exists() and path.is_dir:
        try:
            path.mkdir(parents=True)
        except OSError as e:
            raise CTAFbaseException(ErrorCodeEnum.GET_FILE_PATH_ERROR, "make new directory error: "+str(path))


def load_json_file(filename: str, abs_file_path: Path = None) -> dict | None:
    filepath: Path = get_file_path(filename, abs_file_path)

    if filepath.exists():
        with open(filepath, mode="r", encoding="UTF-8") as f:
            data: dict = json.load(f)
        return data

def save_json_file(filename: str, data: dict) -> None:
    """
    Save data into json file in temp path.
    """
    filepath: Path = get_file_path(filename)
    with open(filepath, mode="w+", encoding="UTF-8") as f:
        json.dump(
            data,
            f,
            indent=4,
            ensure_ascii=False
        )
